/*!
 * \file test_network_communication_comprehensive.cpp
 * \project WonderTrader
 * 
 * \author C++测试专家
 * \date 2024/12/19
 * 
 * \brief 网络通信模块综合测试
 * 
 * \details 本文件包含WonderTrader网络通信模块的全面测试，涵盖：
 *          - TCP/UDP通信组件测试
 *          - 连接池管理测试
 *          - 协议解析器测试
 *          - 网络异常处理测试
 *          - 心跳机制测试
 *          - 数据传输完整性测试
 *          - 并发连接测试
 *          - 网络性能测试
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <thread>
#include <chrono>
#include <atomic>
#include <vector>
#include <string>
#include <memory>
#include <future>
#include <random>
#include <algorithm>
#include <queue>
#include <mutex>
#include <condition_variable>

using namespace std;
using namespace std::chrono;
using namespace testing;

/*! 
 * \brief 模拟网络连接状态枚举
 */
enum class NetworkState {
    DISCONNECTED,   ///< 断开连接
    CONNECTING,     ///< 正在连接
    CONNECTED,      ///< 已连接
    RECONNECTING,   ///< 正在重连
    ERROR_STATE     ///< 错误状态
};

/*!
 * \brief 模拟网络消息结构
 */
struct NetworkMessage {
    uint32_t msg_id;        ///< 消息ID
    uint32_t msg_type;      ///< 消息类型
    uint32_t data_length;   ///< 数据长度
    std::vector<uint8_t> data;  ///< 消息数据
    
    NetworkMessage() : msg_id(0), msg_type(0), data_length(0) {}
    
    NetworkMessage(uint32_t id, uint32_t type, const std::vector<uint8_t>& msg_data)
        : msg_id(id), msg_type(type), data_length(msg_data.size()), data(msg_data) {}
};

/*!
 * \brief 模拟网络连接接口
 */
class INetworkConnection {
public:
    virtual ~INetworkConnection() = default;
    
    /*!
     * \brief 连接到服务器
     * \param host 主机地址
     * \param port 端口号
     * \return 连接是否成功
     */
    virtual bool connect(const std::string& host, uint16_t port) = 0;
    
    /*!
     * \brief 断开连接
     */
    virtual void disconnect() = 0;
    
    /*!
     * \brief 检查连接状态
     * \return 是否已连接
     */
    virtual bool isConnected() const = 0;
    
    /*!
     * \brief 发送数据
     * \param data 要发送的数据
     * \param length 数据长度
     * \return 实际发送的字节数
     */
    virtual int send(const void* data, size_t length) = 0;
    
    /*!
     * \brief 接收数据
     * \param buffer 接收缓冲区
     * \param length 缓冲区大小
     * \return 实际接收的字节数
     */
    virtual int receive(void* buffer, size_t length) = 0;
    
    /*!
     * \brief 获取连接状态
     * \return 当前连接状态
     */
    virtual NetworkState getState() const = 0;
    
    /*!
     * \brief 设置超时时间
     * \param timeout_ms 超时时间（毫秒）
     */
    virtual void setTimeout(uint32_t timeout_ms) = 0;
};

/*!
 * \brief 模拟TCP连接实现
 */
class MockTcpConnection : public INetworkConnection {
private:
    std::string host_;
    uint16_t port_;
    NetworkState state_;
    uint32_t timeout_ms_;
    std::atomic<bool> connected_;
    std::queue<std::vector<uint8_t>> send_queue_;
    std::queue<std::vector<uint8_t>> recv_queue_;
    mutable std::mutex queue_mutex_;
    
public:
    MockTcpConnection() 
        : port_(0), state_(NetworkState::DISCONNECTED), 
          timeout_ms_(5000), connected_(false) {}
    
    virtual ~MockTcpConnection() {
        disconnect();
    }
    
    bool connect(const std::string& host, uint16_t port) override {
        std::lock_guard<std::mutex> lock(queue_mutex_);
        host_ = host;
        port_ = port;
        
        // 模拟连接过程
        state_ = NetworkState::CONNECTING;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        
        // 模拟连接成功/失败
        if (host == "invalid_host" || port == 0) {
            state_ = NetworkState::ERROR_STATE;
            connected_ = false;
            return false;
        }
        
        state_ = NetworkState::CONNECTED;
        connected_ = true;
        return true;
    }
    
    void disconnect() override {
        std::lock_guard<std::mutex> lock(queue_mutex_);
        state_ = NetworkState::DISCONNECTED;
        connected_ = false;
        
        // 清空队列
        while (!send_queue_.empty()) send_queue_.pop();
        while (!recv_queue_.empty()) recv_queue_.pop();
    }
    
    bool isConnected() const override {
        return connected_.load();
    }
    
    int send(const void* data, size_t length) override {
        if (!isConnected()) return -1;
        
        std::lock_guard<std::mutex> lock(queue_mutex_);
        std::vector<uint8_t> buffer(static_cast<const uint8_t*>(data), 
                                   static_cast<const uint8_t*>(data) + length);
        send_queue_.push(buffer);
        return static_cast<int>(length);
    }
    
    int receive(void* buffer, size_t length) override {
        if (!isConnected()) return -1;
        
        std::lock_guard<std::mutex> lock(queue_mutex_);
        if (recv_queue_.empty()) return 0;
        
        auto& data = recv_queue_.front();
        size_t copy_size = std::min(length, data.size());
        memcpy(buffer, data.data(), copy_size);
        recv_queue_.pop();
        
        return static_cast<int>(copy_size);
    }
    
    NetworkState getState() const override {
        return state_;
    }
    
    void setTimeout(uint32_t timeout_ms) override {
        timeout_ms_ = timeout_ms;
    }
    
    // 测试辅助方法
    void simulateReceiveData(const std::vector<uint8_t>& data) {
        std::lock_guard<std::mutex> lock(queue_mutex_);
        recv_queue_.push(data);
    }
    
    std::vector<uint8_t> getLastSentData() {
        std::lock_guard<std::mutex> lock(queue_mutex_);
        if (send_queue_.empty()) return {};
        auto data = send_queue_.front();
        send_queue_.pop();
        return data;
    }
    
    size_t getSendQueueSize() const {
        std::lock_guard<std::mutex> lock(queue_mutex_);
        return send_queue_.size();
    }
};

/*!
 * \brief 模拟UDP连接实现
 */
class MockUdpConnection : public INetworkConnection {
private:
    std::string host_;
    uint16_t port_;
    NetworkState state_;
    uint32_t timeout_ms_;
    std::atomic<bool> bound_;
    std::vector<NetworkMessage> sent_messages_;
    std::vector<NetworkMessage> received_messages_;
    mutable std::mutex message_mutex_;
    
public:
    MockUdpConnection() 
        : port_(0), state_(NetworkState::DISCONNECTED), 
          timeout_ms_(1000), bound_(false) {}
    
    bool connect(const std::string& host, uint16_t port) override {
        std::lock_guard<std::mutex> lock(message_mutex_);
        host_ = host;
        port_ = port;
        
        // UDP是无连接的，这里模拟绑定过程
        if (port == 0) {
            state_ = NetworkState::ERROR_STATE;
            bound_ = false;
            return false;
        }
        
        state_ = NetworkState::CONNECTED;
        bound_ = true;
        return true;
    }
    
    void disconnect() override {
        std::lock_guard<std::mutex> lock(message_mutex_);
        state_ = NetworkState::DISCONNECTED;
        bound_ = false;
        sent_messages_.clear();
        received_messages_.clear();
    }
    
    bool isConnected() const override {
        return bound_.load();
    }
    
    int send(const void* data, size_t length) override {
        if (!isConnected()) return -1;
        
        std::lock_guard<std::mutex> lock(message_mutex_);
        std::vector<uint8_t> buffer(static_cast<const uint8_t*>(data), 
                                   static_cast<const uint8_t*>(data) + length);
        
        NetworkMessage msg(sent_messages_.size() + 1, 1, buffer);
        sent_messages_.push_back(msg);
        
        return static_cast<int>(length);
    }
    
    int receive(void* buffer, size_t length) override {
        if (!isConnected()) return -1;
        
        std::lock_guard<std::mutex> lock(message_mutex_);
        if (received_messages_.empty()) return 0;
        
        auto& msg = received_messages_.front();
        size_t copy_size = std::min(length, msg.data.size());
        memcpy(buffer, msg.data.data(), copy_size);
        received_messages_.erase(received_messages_.begin());
        
        return static_cast<int>(copy_size);
    }
    
    NetworkState getState() const override {
        return state_;
    }
    
    void setTimeout(uint32_t timeout_ms) override {
        timeout_ms_ = timeout_ms;
    }
    
    // 测试辅助方法
    void simulateReceiveMessage(const NetworkMessage& msg) {
        std::lock_guard<std::mutex> lock(message_mutex_);
        received_messages_.push_back(msg);
    }
    
    std::vector<NetworkMessage> getSentMessages() const {
        std::lock_guard<std::mutex> lock(message_mutex_);
        return sent_messages_;
    }
};

/*!
 * \brief 连接池管理器
 */
class ConnectionPool {
private:
    std::vector<std::unique_ptr<INetworkConnection>> connections_;
    std::queue<size_t> available_connections_;
    mutable std::mutex pool_mutex_;
    size_t max_connections_;
    
public:
    /*!
     * \brief 构造函数
     * \param max_connections 最大连接数
     */
    explicit ConnectionPool(size_t max_connections = 10) 
        : max_connections_(max_connections) {
        connections_.reserve(max_connections);
    }
    
    /*!
     * \brief 析构函数
     */
    ~ConnectionPool() {
        clear();
    }
    
    /*!
     * \brief 获取一个可用连接
     * \return 连接索引，-1表示无可用连接
     */
    int getConnection() {
        std::lock_guard<std::mutex> lock(pool_mutex_);
        
        if (!available_connections_.empty()) {
            size_t index = available_connections_.front();
            available_connections_.pop();
            return static_cast<int>(index);
        }
        
        // 如果没有可用连接且未达到最大连接数，创建新连接
        if (connections_.size() < max_connections_) {
            auto new_connection = std::make_unique<MockTcpConnection>();
            connections_.push_back(std::move(new_connection));
            return static_cast<int>(connections_.size() - 1);
        }
        
        return -1; // 无可用连接
    }
    
    /*!
     * \brief 归还连接到连接池
     * \param index 连接索引
     */
    void returnConnection(size_t index) {
        std::lock_guard<std::mutex> lock(pool_mutex_);
        if (index < connections_.size()) {
            // 断开连接并归还到可用连接队列
            connections_[index]->disconnect();
            available_connections_.push(index);
        }
    }
    
    /*!
     * \brief 获取连接指针
     * \param index 连接索引
     * \return 连接指针，nullptr表示无效索引
     */
    INetworkConnection* getConnectionPtr(size_t index) {
        std::lock_guard<std::mutex> lock(pool_mutex_);
        if (index < connections_.size()) {
            return connections_[index].get();
        }
        return nullptr;
    }
    
    /*!
     * \brief 获取连接池大小
     * \return 当前连接数
     */
    size_t size() const {
        std::lock_guard<std::mutex> lock(pool_mutex_);
        return connections_.size();
    }
    
    /*!
     * \brief 获取可用连接数
     * \return 可用连接数
     */
    size_t availableCount() const {
        std::lock_guard<std::mutex> lock(pool_mutex_);
        return available_connections_.size();
    }
    
    /*!
     * \brief 清空连接池
     */
    void clear() {
        std::lock_guard<std::mutex> lock(pool_mutex_);
        connections_.clear();
        while (!available_connections_.empty()) {
            available_connections_.pop();
        }
    }
};

/*!
 * \brief 网络通信综合测试夹具类
 */
class NetworkCommunicationTest : public ::testing::Test {
protected:
    void SetUp() override {
        tcp_connection_ = std::make_unique<MockTcpConnection>();
        udp_connection_ = std::make_unique<MockUdpConnection>();
        connection_pool_ = std::make_unique<ConnectionPool>(5);
    }
    
    void TearDown() override {
        if (tcp_connection_) {
            tcp_connection_->disconnect();
        }
        if (udp_connection_) {
            udp_connection_->disconnect();
        }
        connection_pool_->clear();
    }
    
    std::unique_ptr<MockTcpConnection> tcp_connection_;
    std::unique_ptr<MockUdpConnection> udp_connection_;
    std::unique_ptr<ConnectionPool> connection_pool_;
};

/*!
 * \brief 测试TCP连接建立
 * 验证TCP连接的基本连接功能
 */
TEST_F(NetworkCommunicationTest, TestTcpConnectionEstablishment) {
    // 测试成功连接
    EXPECT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    EXPECT_TRUE(tcp_connection_->isConnected());
    EXPECT_EQ(tcp_connection_->getState(), NetworkState::CONNECTED);
    
    // 测试断开连接
    tcp_connection_->disconnect();
    EXPECT_FALSE(tcp_connection_->isConnected());
    EXPECT_EQ(tcp_connection_->getState(), NetworkState::DISCONNECTED);
}

/*!
 * \brief 测试TCP连接失败场景
 * 验证无效主机和端口的处理
 */
TEST_F(NetworkCommunicationTest, TestTcpConnectionFailure) {
    // 测试无效主机
    EXPECT_FALSE(tcp_connection_->connect("invalid_host", 8080));
    EXPECT_FALSE(tcp_connection_->isConnected());
    EXPECT_EQ(tcp_connection_->getState(), NetworkState::ERROR_STATE);
    
    // 重置连接状态
    tcp_connection_ = std::make_unique<MockTcpConnection>();
    
    // 测试无效端口
    EXPECT_FALSE(tcp_connection_->connect("127.0.0.1", 0));
    EXPECT_FALSE(tcp_connection_->isConnected());
    EXPECT_EQ(tcp_connection_->getState(), NetworkState::ERROR_STATE);
}

/*!
 * \brief 测试TCP数据发送
 * 验证TCP数据发送功能
 */
TEST_F(NetworkCommunicationTest, TestTcpDataSending) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    // 测试发送字符串数据
    std::string test_data = "Hello, TCP World!";
    int sent_bytes = tcp_connection_->send(test_data.c_str(), test_data.length());
    EXPECT_EQ(sent_bytes, static_cast<int>(test_data.length()));
    
    // 验证发送的数据
    auto sent_data = tcp_connection_->getLastSentData();
    EXPECT_EQ(sent_data.size(), test_data.length());
    EXPECT_EQ(std::string(sent_data.begin(), sent_data.end()), test_data);
}

/*!
 * \brief 测试TCP数据接收
 * 验证TCP数据接收功能
 */
TEST_F(NetworkCommunicationTest, TestTcpDataReceiving) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    // 模拟接收数据
    std::string test_data = "Hello from server!";
    std::vector<uint8_t> data_vector(test_data.begin(), test_data.end());
    tcp_connection_->simulateReceiveData(data_vector);
    
    // 接收数据
    char buffer[1024] = {0};
    int received_bytes = tcp_connection_->receive(buffer, sizeof(buffer));
    EXPECT_EQ(received_bytes, static_cast<int>(test_data.length()));
    EXPECT_STREQ(buffer, test_data.c_str());
}

/*!
 * \brief 测试TCP超时设置
 * 验证TCP连接超时参数设置
 */
TEST_F(NetworkCommunicationTest, TestTcpTimeout) {
    tcp_connection_->setTimeout(3000);
    
    // 连接应该正常工作
    EXPECT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    EXPECT_TRUE(tcp_connection_->isConnected());
    
    // 测试在未连接状态下发送数据
    tcp_connection_->disconnect();
    std::string test_data = "test";
    EXPECT_EQ(tcp_connection_->send(test_data.c_str(), test_data.length()), -1);
}

/*!
 * \brief 测试网络连接重连机制
 * 验证网络断开后的重连功能
 */
TEST_F(NetworkCommunicationTest, TestNetworkReconnection) {
    // 建立初始连接
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    EXPECT_TRUE(tcp_connection_->isConnected());
    
    // 模拟网络断开
    tcp_connection_->disconnect();
    EXPECT_FALSE(tcp_connection_->isConnected());
    
    // 重新连接
    EXPECT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    EXPECT_TRUE(tcp_connection_->isConnected());
    EXPECT_EQ(tcp_connection_->getState(), NetworkState::CONNECTED);
}

/*!
 * \brief 测试网络错误状态处理
 * 验证各种网络错误状态的处理
 */
TEST_F(NetworkCommunicationTest, TestNetworkErrorHandling) {
    // 测试连接到无效地址
    EXPECT_FALSE(tcp_connection_->connect("invalid_host", 8080));
    EXPECT_EQ(tcp_connection_->getState(), NetworkState::ERROR_STATE);
    
    // 在错误状态下尝试发送数据
    std::string test_data = "test data";
    EXPECT_EQ(tcp_connection_->send(test_data.c_str(), test_data.length()), -1);
    
    // 在错误状态下尝试接收数据
    char buffer[1024];
    EXPECT_EQ(tcp_connection_->receive(buffer, sizeof(buffer)), -1);
}

/*!
 * \brief 测试UDP连接绑定
 * 验证UDP连接的绑定功能
 */
TEST_F(NetworkCommunicationTest, TestUdpConnectionBinding) {
    // 测试成功绑定
    EXPECT_TRUE(udp_connection_->connect("0.0.0.0", 9090));
    EXPECT_TRUE(udp_connection_->isConnected());
    EXPECT_EQ(udp_connection_->getState(), NetworkState::CONNECTED);
    
    // 测试断开连接
    udp_connection_->disconnect();
    EXPECT_FALSE(udp_connection_->isConnected());
    EXPECT_EQ(udp_connection_->getState(), NetworkState::DISCONNECTED);
}

/*!
 * \brief 测试UDP消息发送
 * 验证UDP消息发送功能
 */
TEST_F(NetworkCommunicationTest, TestUdpMessageSending) {
    ASSERT_TRUE(udp_connection_->connect("127.0.0.1", 9090));
    
    // 发送多条消息
    std::vector<std::string> test_messages = {
        "UDP Message 1",
        "UDP Message 2",
        "UDP Message 3"
    };
    
    for (const auto& msg : test_messages) {
        int sent_bytes = udp_connection_->send(msg.c_str(), msg.length());
        EXPECT_EQ(sent_bytes, static_cast<int>(msg.length()));
    }
    
    // 验证发送的消息数量
    auto sent_messages = static_cast<MockUdpConnection*>(udp_connection_.get())->getSentMessages();
    EXPECT_EQ(sent_messages.size(), test_messages.size());
    
    // 验证消息内容
    for (size_t i = 0; i < test_messages.size(); ++i) {
        std::string sent_content(sent_messages[i].data.begin(), sent_messages[i].data.end());
        EXPECT_EQ(sent_content, test_messages[i]);
    }
}

/*!
 * \brief 测试UDP消息接收
 * 验证UDP消息接收功能
 */
TEST_F(NetworkCommunicationTest, TestUdpMessageReceiving) {
    ASSERT_TRUE(udp_connection_->connect("127.0.0.1", 9090));
    
    // 模拟接收消息
    std::string test_message = "UDP broadcast message";
    std::vector<uint8_t> data_vector(test_message.begin(), test_message.end());
    NetworkMessage msg(1, 100, data_vector);
    
    static_cast<MockUdpConnection*>(udp_connection_.get())->simulateReceiveMessage(msg);
    
    // 接收消息
    char buffer[1024] = {0};
    int received_bytes = udp_connection_->receive(buffer, sizeof(buffer));
    EXPECT_EQ(received_bytes, static_cast<int>(test_message.length()));
    EXPECT_STREQ(buffer, test_message.c_str());
}

/*!
 * \brief 测试连接池基本功能
 * 验证连接池的获取和归还功能
 */
TEST_F(NetworkCommunicationTest, TestConnectionPoolBasicOperations) {
    // 测试获取连接
    int conn_index1 = connection_pool_->getConnection();
    EXPECT_GE(conn_index1, 0);
    EXPECT_EQ(connection_pool_->size(), 1);
    
    int conn_index2 = connection_pool_->getConnection();
    EXPECT_GE(conn_index2, 0);
    EXPECT_NE(conn_index1, conn_index2);
    EXPECT_EQ(connection_pool_->size(), 2);
    
    // 测试归还连接
    connection_pool_->returnConnection(conn_index1);
    EXPECT_EQ(connection_pool_->availableCount(), 1);
    
    // 测试重用连接
    int conn_index3 = connection_pool_->getConnection();
    EXPECT_EQ(conn_index3, conn_index1); // 应该重用之前归还的连接
}

/*!
 * \brief 测试连接池容量限制
 * 验证连接池的最大容量限制
 */
TEST_F(NetworkCommunicationTest, TestConnectionPoolCapacityLimit) {
    // 获取所有可用连接（最大5个）
    std::vector<int> connections;
    for (int i = 0; i < 5; ++i) {
        int conn_index = connection_pool_->getConnection();
        EXPECT_GE(conn_index, 0);
        connections.push_back(conn_index);
    }
    
    EXPECT_EQ(connection_pool_->size(), 5);
    EXPECT_EQ(connection_pool_->availableCount(), 0);
    
    // 尝试获取超出容量的连接
    int extra_conn = connection_pool_->getConnection();
    EXPECT_EQ(extra_conn, -1); // 应该返回-1表示无可用连接
    
    // 归还一个连接后应该可以再次获取
    connection_pool_->returnConnection(connections[0]);
    EXPECT_EQ(connection_pool_->availableCount(), 1);
    
    int reused_conn = connection_pool_->getConnection();
    EXPECT_EQ(reused_conn, connections[0]);
}

/*!
 * \brief 测试连接池并发访问
 * 验证连接池在多线程环境下的安全性
 */
TEST_F(NetworkCommunicationTest, TestConnectionPoolConcurrency) {
    const int num_threads = 10;
    const int operations_per_thread = 100;
    std::vector<std::thread> threads;
    std::atomic<int> successful_operations(0);
    
    // 启动多个线程同时操作连接池
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back([&]() {
            for (int j = 0; j < operations_per_thread; ++j) {
                int conn_index = connection_pool_->getConnection();
                if (conn_index >= 0) {
                    // 模拟使用连接
                    std::this_thread::sleep_for(std::chrono::microseconds(1));
                    connection_pool_->returnConnection(conn_index);
                    successful_operations++;
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证操作结果
    EXPECT_GT(successful_operations.load(), 0);
    EXPECT_LE(connection_pool_->size(), 5); // 不应超过最大容量
}

/*!
 * \brief 测试网络通信性能
 * 验证大量数据传输的性能表现
 */
TEST_F(NetworkCommunicationTest, TestNetworkPerformance) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    const int num_messages = 1000;
    const size_t message_size = 1024;
    std::vector<uint8_t> test_data(message_size, 0xAB);
    
    auto start_time = high_resolution_clock::now();
    
    // 发送大量数据
    for (int i = 0; i < num_messages; ++i) {
        int sent_bytes = tcp_connection_->send(test_data.data(), test_data.size());
        EXPECT_EQ(sent_bytes, static_cast<int>(message_size));
    }
    
    auto end_time = high_resolution_clock::now();
    auto duration = duration_cast<milliseconds>(end_time - start_time);
    
    // 验证性能指标
    EXPECT_LT(duration.count(), 1000); // 应该在1秒内完成
    EXPECT_EQ(tcp_connection_->getSendQueueSize(), num_messages);
    
    // 计算吞吐量
    double throughput_mbps = (num_messages * message_size * 8.0) / (duration.count() * 1000.0);
    EXPECT_GT(throughput_mbps, 1.0); // 至少1 Mbps
}

/*!
 * \brief 测试UDP广播性能
 * 验证UDP广播消息的性能
 */
TEST_F(NetworkCommunicationTest, TestUdpBroadcastPerformance) {
    ASSERT_TRUE(udp_connection_->connect("255.255.255.255", 9090));
    
    const int num_broadcasts = 500;
    const size_t message_size = 512;
    std::vector<uint8_t> broadcast_data(message_size, 0xCD);
    
    auto start_time = high_resolution_clock::now();
    
    // 发送广播消息
    for (int i = 0; i < num_broadcasts; ++i) {
        int sent_bytes = udp_connection_->send(broadcast_data.data(), broadcast_data.size());
        EXPECT_EQ(sent_bytes, static_cast<int>(message_size));
    }
    
    auto end_time = high_resolution_clock::now();
    auto duration = duration_cast<milliseconds>(end_time - start_time);
    
    // 验证性能指标
    EXPECT_LT(duration.count(), 500); // 应该在500毫秒内完成
    
    auto sent_messages = static_cast<MockUdpConnection*>(udp_connection_.get())->getSentMessages();
    EXPECT_EQ(sent_messages.size(), num_broadcasts);
}

/*!
 * \brief 测试数据传输完整性
 * 验证数据在传输过程中的完整性
 */
TEST_F(NetworkCommunicationTest, TestDataIntegrity) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    // 生成随机测试数据
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<uint8_t> dis(0, 255);
    
    std::vector<uint8_t> original_data(2048);
    for (auto& byte : original_data) {
        byte = dis(gen);
    }
    
    // 发送数据
    int sent_bytes = tcp_connection_->send(original_data.data(), original_data.size());
    EXPECT_EQ(sent_bytes, static_cast<int>(original_data.size()));
    
    // 获取发送的数据并验证
    auto sent_data = tcp_connection_->getLastSentData();
    EXPECT_EQ(sent_data.size(), original_data.size());
    EXPECT_EQ(sent_data, original_data);
    
    // 模拟接收相同数据
    tcp_connection_->simulateReceiveData(original_data);
    
    // 接收并验证数据
    std::vector<uint8_t> received_data(original_data.size());
    int received_bytes = tcp_connection_->receive(received_data.data(), received_data.size());
    EXPECT_EQ(received_bytes, static_cast<int>(original_data.size()));
    EXPECT_EQ(received_data, original_data);
}

/*!
 * \brief 测试大数据包传输
 * 验证大数据包的传输能力
 */
TEST_F(NetworkCommunicationTest, TestLargeDataPacketTransmission) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    // 创建大数据包（1MB）
    const size_t large_packet_size = 1024 * 1024;
    std::vector<uint8_t> large_data(large_packet_size);
    
    // 填充模式数据
    for (size_t i = 0; i < large_packet_size; ++i) {
        large_data[i] = static_cast<uint8_t>(i % 256);
    }
    
    // 发送大数据包
    int sent_bytes = tcp_connection_->send(large_data.data(), large_data.size());
    EXPECT_EQ(sent_bytes, static_cast<int>(large_packet_size));
    
    // 验证发送的数据
    auto sent_data = tcp_connection_->getLastSentData();
    EXPECT_EQ(sent_data.size(), large_packet_size);
    
    // 验证数据模式
    for (size_t i = 0; i < std::min(size_t(1000), sent_data.size()); ++i) {
        EXPECT_EQ(sent_data[i], static_cast<uint8_t>(i % 256));
    }
}

/*!
 * \brief 心跳管理器类
 */
class HeartbeatManager {
private:
    std::atomic<bool> running_;
    std::thread heartbeat_thread_;
    std::chrono::milliseconds interval_;
    std::function<void()> heartbeat_callback_;
    std::atomic<int> heartbeat_count_;
    
public:
    HeartbeatManager(std::chrono::milliseconds interval, std::function<void()> callback)
        : running_(false), interval_(interval), heartbeat_callback_(callback), heartbeat_count_(0) {}
    
    ~HeartbeatManager() {
        stop();
    }
    
    void start() {
        if (running_.load()) return;
        
        running_ = true;
        heartbeat_thread_ = std::thread([this]() {
            while (running_.load()) {
                std::this_thread::sleep_for(interval_);
                if (running_.load() && heartbeat_callback_) {
                    heartbeat_callback_();
                    heartbeat_count_++;
                }
            }
        });
    }
    
    void stop() {
        running_ = false;
        if (heartbeat_thread_.joinable()) {
            heartbeat_thread_.join();
        }
    }
    
    int getHeartbeatCount() const {
        return heartbeat_count_.load();
    }
    
    bool isRunning() const {
        return running_.load();
    }
};

/*!
 * \brief 测试心跳机制
 * 验证网络连接的心跳保活功能
 */
TEST_F(NetworkCommunicationTest, TestHeartbeatMechanism) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    std::atomic<int> heartbeat_sent(0);
    
    // 创建心跳管理器
    HeartbeatManager heartbeat_mgr(std::chrono::milliseconds(50), [&]() {
        if (tcp_connection_->isConnected()) {
            std::string heartbeat_msg = "HEARTBEAT";
            tcp_connection_->send(heartbeat_msg.c_str(), heartbeat_msg.length());
            heartbeat_sent++;
        }
    });
    
    // 启动心跳
    heartbeat_mgr.start();
    EXPECT_TRUE(heartbeat_mgr.isRunning());
    
    // 等待几个心跳周期
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    
    // 停止心跳
    heartbeat_mgr.stop();
    EXPECT_FALSE(heartbeat_mgr.isRunning());
    
    // 验证心跳发送
    EXPECT_GT(heartbeat_sent.load(), 0);
    EXPECT_GE(heartbeat_mgr.getHeartbeatCount(), 3); // 至少发送3次心跳
    EXPECT_GE(tcp_connection_->getSendQueueSize(), 3);
}

/*!
 * \brief 测试心跳超时检测
 * 验证心跳超时的检测和处理
 */
TEST_F(NetworkCommunicationTest, TestHeartbeatTimeoutDetection) {
    ASSERT_TRUE(tcp_connection_->connect("127.0.0.1", 8080));
    
    std::atomic<bool> timeout_detected(false);
    auto last_heartbeat = std::chrono::steady_clock::now();
    const auto timeout_threshold = std::chrono::milliseconds(100);
    
    // 心跳超时检测器
    std::thread timeout_detector([&]() {
        while (tcp_connection_->isConnected() && !timeout_detected.load()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            
            auto now = std::chrono::steady_clock::now();
            if (now - last_heartbeat > timeout_threshold) {
                timeout_detected = true;
                break;
            }
        }
    });
    
    // 模拟心跳停止（不更新last_heartbeat）
    std::this_thread::sleep_for(std::chrono::milliseconds(150));
    
    timeout_detector.join();
    
    // 验证超时检测
    EXPECT_TRUE(timeout_detected.load());
}

/*!
 * \brief 网络通信综合压力测试
 * 验证网络通信在高负载下的稳定性
 */
TEST_F(NetworkCommunicationTest, TestNetworkCommunicationStressTest) {
    const int num_connections = 3; // 受连接池限制
    const int messages_per_connection = 100;
    const size_t message_size = 256;
    
    std::vector<std::thread> worker_threads;
    std::atomic<int> total_messages_sent(0);
    std::atomic<int> total_bytes_sent(0);
    
    // 创建多个工作线程
    for (int i = 0; i < num_connections; ++i) {
        worker_threads.emplace_back([&, i]() {
            int conn_index = connection_pool_->getConnection();
            if (conn_index < 0) return;
            
            auto* connection = connection_pool_->getConnectionPtr(conn_index);
            if (!connection) {
                connection_pool_->returnConnection(conn_index);
                return;
            }
            
            // 建立连接
            if (!connection->connect("127.0.0.1", 8080 + i)) {
                connection_pool_->returnConnection(conn_index);
                return;
            }
            
            // 发送消息
            std::vector<uint8_t> message_data(message_size, 0x55);
            for (int j = 0; j < messages_per_connection; ++j) {
                int sent_bytes = connection->send(message_data.data(), message_data.size());
                if (sent_bytes > 0) {
                    total_messages_sent++;
                    total_bytes_sent += sent_bytes;
                }
                
                // 短暂休眠模拟实际使用
                std::this_thread::sleep_for(std::chrono::microseconds(100));
            }
            
            connection->disconnect();
            connection_pool_->returnConnection(conn_index);
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : worker_threads) {
        thread.join();
    }
    
    // 验证压力测试结果
    EXPECT_GT(total_messages_sent.load(), 0);
    EXPECT_GT(total_bytes_sent.load(), 0);
    
    // 验证消息发送效率
    int expected_total_messages = num_connections * messages_per_connection;
    double success_rate = static_cast<double>(total_messages_sent.load()) / expected_total_messages;
    EXPECT_GT(success_rate, 0.8); // 至少80%的消息发送成功
} 